#include<string>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include "ThreadPool/log.hpp"

static void Usage(const std::string proc)
{
    std::cout<<"\nUsage: " << proc << " tcpserver ip port" << std::endl;
}

// ./tcp_client ip port
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std:: string serverip  = argv[1];
    uint16_t serverport  = atoi(argv[2]);

    // 1. 创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        std::cerr<<"socket error"<<std::endl;
        exit(2);
    }
    // client 不需要显示的bind，但是一定是需要port
    // 需要让os自动进行port选择

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport );

    // 2. 连接
    if(connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(3); 
    }
    std::cout << "connect success" << std::endl;

    // 3. 收发消息
    while(true)
    {
        std::string line;
        std::cout << "请输入# ";
        std::getline(std::cin, line);
        if(line == "quit")
            break;
        
        // connect后可以直接使用send与recv
        ssize_t s = send(sock, line.c_str(), line.size(), 0); // 0阻塞式通信

        if(s > 0)
        {
            char buffer[1024];
            ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
            buffer[s] = 0;
            std::cout << "server 回显# " << buffer << std::endl;
        }
        else if(s == 0)
        {
            break;
        }
        else 
        {
            break;
        }
    }



    return 0;
}